package dao

import (
	"context"
	"fabric-explorer/entity"
	"fabric-explorer/tools"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const (
	CHAINCODE_COLLECTION_NAME = "chaincode"
)

//插入Chaincode
func InsertChaincode(chaincode entity.Chaincode) {
	// tools.InitDB()
	collection := tools.GetCollection(CHAINCODE_COLLECTION_NAME)
	insertResult, err := collection.InsertOne(context.TODO(), chaincode)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Inserted a single document: ", insertResult.InsertedID)
}

//查询Chaincode的List
func FindChaincodeList(selecter bson.D) []entity.Chaincode {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	collection := tools.GetCollection(CHAINCODE_COLLECTION_NAME)
	cur, err := collection.Find(ctx, selecter)
	if err != nil {
		fmt.Println(err)
	}
	defer cur.Close(ctx)

	chaincodeList := make([]entity.Chaincode, 0)
	for cur.Next(ctx) {
		chaincode := &entity.Chaincode{}
		err := cur.Decode(chaincode)
		if err != nil {
			fmt.Println(err)
		}
		chaincodeList = append(chaincodeList, *chaincode)
	}
	if err := cur.Err(); err != nil {
		fmt.Println(err)
	}
	return chaincodeList
}

//查询Chaincode的page
func FindChaincodeListPage(selecter bson.D, options *options.FindOptions) []entity.Chaincode {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	collection := tools.GetCollection(CHAINCODE_COLLECTION_NAME)
	cur, err := collection.Find(ctx, selecter, options)
	if err != nil {
		fmt.Println(err)
	}
	defer cur.Close(ctx)

	chaincodeList := make([]entity.Chaincode, 0)
	for cur.Next(ctx) {
		chaincode := &entity.Chaincode{}
		err := cur.Decode(chaincode)
		if err != nil {
			fmt.Println(err)
		}
		chaincodeList = append(chaincodeList, *chaincode)
	}
	if err := cur.Err(); err != nil {
		fmt.Println(err)
	}
	return chaincodeList
}

//查询index
func GetChaincodeNum(selecter bson.D) int64 {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	collection := tools.GetCollection(CHAINCODE_COLLECTION_NAME)
	num, err := collection.CountDocuments(ctx, selecter)
	if err != nil {
		fmt.Println(err)
	}
	return num
}

//删除chaincode
func DeleteChaincode(selecter bson.D) {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	collection := tools.GetCollection(CHAINCODE_COLLECTION_NAME)
	_, err := collection.DeleteMany(ctx, selecter)
	if err != nil {
		fmt.Println(err)
	}
}
